package servlets;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import service.ErrorService;
import service.ValidateInput;
import dao.ParticipantListDAO;
import dao.PlacementListDAO;
import dao.RoleDAO;
import dao.TeamDAO;
import dao.TeamInfoDAO;
import dao.TournamentDAO;
import daoimpl.ParticipantListDAOImpl;
import daoimpl.PlacementListDAOImpl;
import daoimpl.RoleDAOImpl;
import daoimpl.TeamDAOImpl;
import daoimpl.TeamInfoDAOImpl;
import daoimpl.TournamentDAOImpl;
import dto.ParticipantListDTO;
import dto.PlacementListDTO;
import dto.RoleDTO;
import dto.TeamDTO;
import dto.TournamentDTO;
import dto.UserDTO;
import exceptions.DALException;

/**
 * Servlet implementation class TournamentManager
 */
@WebServlet("/TournamentManager")
public class TournamentManager extends HttpServlet {
	private static final long serialVersionUID = 1L;

	private int teamId;
	private String teamName;

	private TournamentDTO tourDTO;
	
	private TeamInfoDAO teamIDAO;
	private TeamDAO teamDAO;
	private TournamentDAO tourDAO;
	private RoleDAO roleDAO;
	private ParticipantListDAO partiDAO;

	private List<TeamDTO> teamMemberList;



	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public TournamentManager() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		UserDTO udto = (UserDTO) request.getSession().getAttribute("userObject");
		String action = request.getParameter("action");
		int tId = Integer.parseInt(request.getParameter("id"));
		System.out.println(tId);

		try {
			teamIDAO = new TeamInfoDAOImpl();
			teamDAO = new TeamDAOImpl();
			roleDAO = new RoleDAOImpl();
			partiDAO = new ParticipantListDAOImpl();
			tourDAO = new TournamentDAOImpl();

		}

		catch(DALException e){

		}

		System.out.println("Action = "+action);

		switch (action) {

		case "StartFinish":


			try {

				tourDTO = tourDAO.getTournament(tId);
				if(partiDAO.getParticipantCount(tId) >= 2){

					if(tourDAO.getTournament(tId).getStatus()==0){
						tourDAO.updateTournament(new TournamentDTO(tId, tourDTO.getTournamentName(), tourDTO.getSport(), tourDTO.getMaxParticipants(), 1, tourDTO.getStartDate(), tourDTO.getInfo(), tourDTO.getTournament_type(), tourDTO.getTournament_format()));
					}
					else if(tourDAO.getTournament(tId).getStatus()==1){
						tourDAO.updateTournament(new TournamentDTO(tId, tourDTO.getTournamentName(), tourDTO.getSport(), tourDTO.getMaxParticipants(), 2, tourDTO.getStartDate(), tourDTO.getInfo(), tourDTO.getTournament_type(), tourDTO.getTournament_format()));
						// Placementlist skal opdateres her
						PlacementListDAO placementDAO = new PlacementListDAOImpl();
						
						for(ParticipantListDTO parti : partiDAO.getParticipantList(tId)){
							placementDAO.createPlacementList(new PlacementListDTO(tId, parti.getTeamId(), 0));
						}
					}
					else{
						System.out.println("Turnering allerede afsluttet");
					}

				}
				
				else{
					System.out.println("Turneringen skal have mindst 2 deltagere");
				}
			} catch (DALException e) {
				ValidateInput validate = new ValidateInput();
				ErrorService error = validate.createError();
				error.setError("<div class=\"alert alert-danger\">"+e+"</div>");
				request.setAttribute("error", error);
			}

			response.sendRedirect(request.getContextPath() + "/TournamentSelector?id=" + tId);

			break;

		case "add team":

			teamName = request.getParameter("name");
			try {
				teamId = teamIDAO.getTeamId(teamName);
			} catch (DALException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
			try {
				if(tourDAO.getTournament(tId).getStatus()==0){
					if(teamIDAO.getTeam(teamId).getSport().equals(tourDAO.getTournament(tId).getSport())){

						partiDAO.createParticipant(new ParticipantListDTO(teamId, tId));

//						List<TeamDTO> teamMemberList = teamDAO.getTeamList(teamId);
						List<TeamDTO> teamMemberList = teamDAO.getMemberList(teamId);

						for(TeamDTO teamMember: teamMemberList){
							roleDAO.createRole(new RoleDTO(teamMember.getUserId(), tId, 2));
						}
					}

				}
				else{
					System.out.println("Cant add teams to a tournament which is ended or in progress");
				}
			} catch (DALException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			response.sendRedirect(request.getContextPath() + "/TournamentSelector?id=" + tId);


			break;

		case "delete team":


			teamName = request.getParameter("name");


			try{
				if(tourDAO.getTournament(tId).getStatus()==0){
					teamId = teamIDAO.getTeamId(teamName);	
					teamMemberList = teamDAO.getMemberList(teamId);

					partiDAO.disableParticipant(new ParticipantListDTO(teamId, tId));

					for(TeamDTO teamMember: teamMemberList){
						roleDAO.disableRole(new RoleDTO(teamMember.getUserId(), tId, 2));
					}
				}
				else{
					System.out.println("Cant remove teams from a tournament which is ended or in progress");
				}
			} catch (DALException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}	

			response.sendRedirect(request.getContextPath() + "/TournamentSelector?id=" + tId);



			break;

		case "edit tournament":

			String tour_name = request.getParameter("tournament_name");
			String sport = request.getParameter("Sport");
			String formatText = request.getParameter("Tournament Type");
			int format;
			if (formatText.equals("type1")) {
				format = 1; // Hvis format = 1 er turneringen open
			} else {
				format = 2; // lukket tur. format
			}
			String pcount = request.getParameter("size");
			String dato = request.getParameter("Starting Date");
			String info = request.getParameter("info");
			String type = request.getParameter("Tournament Format");
			int typeInt;
			if (type.equals("format1")) {
				typeInt = 0; // 0 for single elim. turnering.
			} else {
				typeInt = 1; // 1 for double elim. turnering.
			}
			int size = Integer.parseInt(pcount);
			boolean nameTaken = false;

			try{
				tourDAO = new TournamentDAOImpl();

				for(TournamentDTO tournament: tourDAO.getTournamentList()){
					if(tournament.getTournamentName().equals(tour_name)){
						nameTaken = true;
					}
				}
				if(!nameTaken){
					tourDAO.updateTournament(new TournamentDTO(tId,tour_name, sport, size,0, dato, info, typeInt, format));
				}
			}
			catch(DALException e){
				System.out.println("Fejl i edit tournament " +e);
			}

			response.sendRedirect(request.getContextPath() + "/TournamentSelector?id=" + tId);


			break;

		case "delete tournament":


			try {
				if(tourDAO.getTournament(tId).getStatus()==0){
//					roleDAO.disableRole(new RoleDTO(udto.getId(), tId, 1));
					tourDAO.disableTournament(new TournamentDTO(tId, null, null, 0, 0, null, null, 0, 0));
				}
				else{
					System.out.println("Cant delete a tournament which is ended or in progress");
				}
			} catch (DALException e) {
				System.out.println("Fejl i delete tour");
				e.printStackTrace();
			}

			this.getServletContext().getRequestDispatcher("/WEB-INF/user/Main.jsp").forward(request, response);

			break;


		default:

			System.out.println("missing logic");
			response.sendRedirect(request.getContextPath() + "/TournamentSelector?id=" + tId);

			break;
		}



		try {
			teamIDAO.closeConnection();
			teamDAO.closeConnection();
			tourDAO.closeConnection();
			roleDAO.closeConnection();
			partiDAO.closeConnection();
		} catch (DALException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

}
